package droid.insane.communication;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;

import org.apache.http.util.ByteArrayBuffer;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import droid.insane.logic.ConstantValues;
import droid.insane.logic.StringHandler;
import droid.insane.logic.UpdateFlags;

/**
 * @author Sandamal
 * Downloads data from the cse web server
 */

public class Communicator extends AsyncTask<Void, Integer, String> {

	private static final int APPROX_MAX_FILE_SIZE = 50;
	private static final String address = "http://www.cse.lk/listedcompanies/overview.htm?d-16544-e=1&6578706f7274=1";
	private int fileSize;
	private int bytesRead = 0;
	private int totalRead = 0;
	private String dataString;
	private ProgressDialog pd;
	private String lastUpdated = "N/A";
	private final Context context;

	public Communicator(Context context) {
		this.context = context;
	}

	@Override
	protected void onPreExecute() {

		pd = new ProgressDialog(context);
		pd.setCancelable(true);
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.setTitle("Updating...");
		pd.setMessage("Downloading data...");
		pd.show();
	}

	@Override
	protected String doInBackground(Void... params) {

		try {
			URL fileURL = new URL(address);
			URLConnection ucon = fileURL.openConnection();
			setFileSize(ucon.getContentLength());

			InputStream inStream = ucon.getInputStream();
			BufferedInputStream bufferedInStream = new BufferedInputStream(
					inStream);

			if (fileSize == -1) {
				setFileSize(APPROX_MAX_FILE_SIZE);
			}
			pd.setMax(getFileSize());

			Log.d(ConstantValues.TAG, "Communicator - File size is set to "
					+ getFileSize());

			ByteArrayBuffer byteBuffer = new ByteArrayBuffer(fileSize + 1);

			while ((bytesRead = bufferedInStream.read()) != -1) {
				byteBuffer.append(bytesRead);
				totalRead++;
				publishProgress(totalRead);

			}
			bufferedInStream.close();

			dataString = new String(byteBuffer.toByteArray());

		} catch (Exception e) {
			Log.e(ConstantValues.TAG, e.getMessage());
		}
		return dataString;
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		pd.setProgress(values[0]);
	}

	@Override
	protected void onPostExecute(String result) {
		pd.dismiss();
		ProgressDialog dialog = ProgressDialog.show(context, "",
				"Updating database...", true);

		setLastUpdated(Calendar.getInstance().getTime().toLocaleString());
		StringHandler sh = StringHandler.getStringHandler();
		sh.getData(dataString);
		UpdateFlags.setALL_FLAGS();
		dialog.dismiss();
	}

	public final int getFileSize() {
		return fileSize;
	}

	public final void setFileSize(final int fileSize) {
		this.fileSize = fileSize;
	}

	public String getLastUpdated() {
		return lastUpdated;
	}

	public void setLastUpdated(String lastUpdated) {
		this.lastUpdated = lastUpdated;
	}

}
